package com.warmheart.core.util;

import java.math.BigInteger;

public class HexUtil {

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * 
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 16进制直接转换成为字符串(无需Unicode解码)
     * 
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    // 將10進制轉換為16進制
    public static String encodeHEX(Integer numb) {
        String hex = Integer.toHexString(numb);
        return hex;

    }

    // 將16進制字符串轉換為10進制數字
    public static String decodeHEX(String hexs) {
        BigInteger bigint = new BigInteger(hexs, 16);
        return bigint.toString();
    }

    public static void main(String[] args) {
        // String hexStr =
        // HexUtil.str2HexStr("SOF;ADDR:12345678;CNUM:1234567890;TEMP:35.7;END");
        // System.out.println(hexStr);
        System.out.println(HexUtil.decodeHEX("01ff"));
        // String ret = "5aa51234567802b50915808355";
        // String machineAddr = ret.substring(4, 12);
        // String cardNo = ret.substring(12, 20);
        // String temperature = ret.substring(20, 24);
        // System.out.println(machineAddr);
        // System.out.println(cardNo);
        System.out.println(HexUtil.encodeHEX(2010010001));
    }
}
